﻿using ZR.Model;
using ZR.Model.Souvenir;
using ZR.Model.Souvenir.Dto;
using ZR.Service.Souvenir.IService;

namespace ZR.Service.Souvenir
{
    [AppService(ServiceType = typeof(ICategoryService), ServiceLifetime = LifeTime.Transient)]
    public class CategoryService : BaseService<Category>, ICategoryService
    {
        public async Task<int> InsertCategoryAsync(Category category)
        {
            return await Insertable(category).ExecuteCommandAsync();
        }

        public async Task<int> UpdateCategoryAsync(Category category)
        {
            return await Updateable(category).ExecuteCommandAsync();
        }

        public async Task<int> DeleteCategoryAsync(int categoryId)
        {
            return await Deleteable()
                .Where(it => it.Id == categoryId)
                .ExecuteCommandAsync();
        }

        public async Task<PagedInfo<Category>> SelectCategoryWithPageAsync(CategoryQueryDto categoryQueryDto)
        {
            RefAsync<int> total = 0;
            var exp = Expressionable.Create<Category>();
            var res = await Queryable()
                .Where(exp.ToExpression())
                .ToPageListAsync(categoryQueryDto.PageNum, categoryQueryDto.PageSize, total);
            var page = new PagedInfo<Category>()
            {
                PageIndex = categoryQueryDto.PageNum,
                PageSize = categoryQueryDto.PageSize,
                Result = res,
                TotalNum = total
            };
            return page;
        }

        public async Task<Category> SelectCategoryAsyncById(int categoryId)
        {
            return await Queryable()
                .Where(it => it.Id == categoryId)
                .FirstAsync();
        }

        public async Task<List<Category>> SelectCategoryWithTreeAsync()
        {
            var exp = Expressionable.Create<Category>();
            var res = await Queryable()
                .Where(exp.ToExpression())
                .OrderBy((it) => new { it.ParentId, it.Sort })
                .ToTreeAsync(it => it.Children, it => it.ParentId, 0);
            return res;
        }
    }
}